package com.rainyun.rc.orm;

import com.rainyun.rc.common.VersionUtil;
import com.rainyun.rc.orm.annotation.PrimaryField;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;


public class SqliteDB extends CommonDB{

	String path;

	/**核心orm的构造器*/
	public SqliteDB(String path) {
		this.path = path;
		addClazz(VersionData.class,"versions");
	}
	@Override
	public RainSql newSql(Class<?> clazz) {
		return new SqliteSql(clazz,this);
	}
	
	public String getPath() {
		return path;
	}

	public SqliteDB setPath(String path) {
		this.path = path;
		return this;
	}
	@Override
	public boolean connect() throws SQLException{
		try {
			Class.forName("org.sqlite.JDBC");
			Connection con = connection;
			if(con!=null)//关掉原来连接
				con.close();
			connection = DriverManager.getConnection("jdbc:sqlite:"+path+".db");
			sqlUpdate("PRAGMA foreign_keys = ON;");

			return true;
		} catch (ClassNotFoundException e) {
			handleError(null,e);
		} catch (SQLException e) {
			handleError(null,e);
			throw e;
		}
		return false;
	}

	public static class VersionData{
		@PrimaryField
		String class_name;
		String version;

		public String getClass_name() {
			return class_name;
		}
		public void setClass_name(String class_name) {
			this.class_name = class_name;
		}
		public String getVersion() {
			return version;
		}
		public void setVersion(String version) {
			this.version = version;
		}
	}

	public void setDataVersion(Class<?> c){
		SqliteDB.VersionData data = new SqliteDB.VersionData();
		data.setClass_name(c.getName());
		data.setVersion(VersionUtil.getVersion(c));
		try {
			newSql(SqliteDB.VersionData.class).save(data);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public String getDataVersion(Class<?> c){
		try {
			SqliteDB.VersionData data = newSql(SqliteDB.VersionData.class).find(c.getName());
			return data!=null?data.getVersion():null;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
}
